<?php
                                                                                                                                                                                                                                                                                                                                        
// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      
                                                                                                                                                                     
//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2021/07/27
//      |_|                                         | TpMeCMS

namespace app\api\controller;
use app\api\controller\Tpmecms;
use think\Db;
use think\Config;
use fast\Random;
use fast\Http;
use think\Request;

/**
 * 查询支付🕳💰
 */
class QueryPay extends Tpmecms
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $pay_role = 1;//支付角色 2司机端 1货主端
    public $domain; //  域名
    public $_params;//支付设置
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 阿里查询参数
     * @ApiInternal
     * @param integer $pay_role 支付角色 2司机端 1货主端
     * @return void
     */
    protected function ali_query_params($pay_role=1)
    {
        $config = Config::get('site');
        $params = new \Yurun\PaySDK\AlipayApp\Params\PublicParams();
        if($pay_role==1){
            $params->appID = $config['ali_app_id'];
            $params->apiDomain = $config['ali_apiDomain'];
            $params->format = 'JSON';
            $params->sign_type = 'RSA2';
            $params->usePublicKeyCert = true;
            // 支付宝公钥证书文件路径
            $params->alipayCertPath = './cert/alipayCertPublicKey_RSA2.crt';
            // 支付宝根证书文件路径
            $params->alipayRootCertPath = './cert/alipayRootCert.crt';
            // 支付宝应用公钥证书文件路径
            $params->merchantCertPath = './cert/appCertPublicKey_2021003105661387.crt';

            // $params->aesKey   = 'UlZ8TAMN688HF/MTWDqE2g==';
            //应用公钥2048
            $params->appPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgu1NlQM8kIhHzYsNPl46SiKjUtz2E6YrGTdeNE4YijeX7zOHtYxNxzAb5aR4kSuUdJL7mwpa9t+gY/qthWFlrQnQ5jFtTwNVP5rGt4gJ2cs3DHrr1TksiHZKvXGtPTQcVGPyaDXnRNgxO6OdGoJzKbFJmctpIc/9fNIiLKeCfT5s8jPrxwAYQUTzWRMqCQdPgaF1OnB2KWQ2ZHtI3YYx2j8qJK4rMTTYmPS7Xcn0Eln6iE8S5/vLpe6h8LYGKMRiNiBzb27wC2hyFRD4BBqk6n9iGSarBHk9E0Pqv0lIAaGKkqnaJNkTWksvhQBLUzCk4Z3ZqfHKsGD0ftHwbrMHpQIDAQAB';
            //应用私钥2048.txt   支付宝开发工具生成
            $params->appPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCidx5KvTI/ZSHzMTnCCXAqVhn/KVkMeE9juZ5oPoAzznq/IKiOCNFENiHVwor0INnEjE119+5R9RCs3Ud2E/RLG/3apaGvR401SufH3fT6WOfETvd5L4O27Akapy58Db/UHJP9VGA8on90//YtEhveS0qci3b/W0aP/BavWGNuW1Ja7nmrEomlMPYFGOxbt+Z96xNkpudRC92Hqy9SHIe9gh3bAfON6J+8J6mkXQ6S5+bwk7PpPojLL+LQmZtIxwX125jzfjPYbAmmf0Y1iRfkeQ9D45L62EiJNxCI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GE1Hh5s2DA+qIsZ8tfhlfJDPwKBgAicnhA49D+7/Sgle9yo1xB/q8L6mWd40FxCH1DQfA1lJ4Ix4TDdILRXfbBbJLqBHEf4HADOON0gvc2WMQt7EEYnCv4R13/8cAYSN0HaeS6pQFJfwT74DdQa8jw1JuBGhxMaIRn2v10LVKjtIUfoUBpk3u06KkPpgpnLp+rPsr1V';
        }else{ 
            $params->appID = $config['driver_ali_app_id'];
            $params->apiDomain = $config['driver_ali_apiDomain'];
            //应用公钥2048
            $params->appPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlsxYl24wNXmEIwUmNpalU0WXooBE4BiTXiMrNiZeFDJQxLJ0E+tq0a9PLSxHtSoCEpopv/UWPUB9JpxV2ZRe/HexC8lW70NG9uNQURzVD/0NQMTCu8zTMygMxDyaJ1AS+HtoD/oSoiQ/kNDrvLRpUAmss+DYPWxZtuLx4kIDkIjZ8ZkrShTGFcGr7EhUkmsGIWUxdmtq4HG/Lp7noW1yMBUUWUUFMqfr0dKu4c+e1Eiz73dPPhyGOroD8ZZt1BfkU7kKv1qKP01luiqles7eByS29pMu9UTOdZi11QCloJp5S6BByYov+LDNn2YkAr/fXbfRwnOvqAgnmd3sn0FnsQIDAQAB';//$appPublicKey;
            //应用私钥2048.txt   支付宝开发工具生成
            $params->appPrivateKey ='MIIEpAIBAAKCAQEAlsxYl24wNXmEIwUmNpalU0WXooBE4BiTXiMrNiZeFDJQxLJ0E+tq0a9PLSxHtSoCEpopv/UWPUB9JpxV2ZRe/HexC8lW70NG9uNQURzVD/0NQMTCu8zTMygMxDyaJ1AS+HtoD/oSoiQ/kNDrvLRpUAmss+DYPWxZtuLx4kIDkIjZ8ZkrShTGFcGr7EhUkmsGIWUxdmtq4HG/Lp7noW1yMBUUWUUFMqfr0dKu4c+e1Eiz73dPPhyGOroD8ZZt1BfkU7kKv1qKP01luiqles7eByS29pMu9UTOdZi11QCloJp5S6BByYov+LDNn2YkAr/fXb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d0aPQKBgQCCAP9mydZr0OxwAgvn8kHmyQBPcNDwUO7sgYaDplxEKFiYKAhgFDA6pyP8vbQKXWRnl3mm54U8yKMqBBOgjWgX9fJjx7r2j2sRuSbJy8xw1w6y/Uxo5wzH+qaxev/vGQ3wJTzcDf3w1i4I4BCDnTbut1MnEE/mV0WiYIuFkA/5Gg==';
        
        }
        return $params;
    }

    // public function __construct($pay_role)
    // {
    //     if(isset($pay_role))
    //     $this->pay_role = $pay_role;
    //     $request = Request::instance();
    //     $this->domain = $request->domain();
    // }


    // /**
    //  * @ApiInternal
    //  * 🔐获取微信支付配置
    //  *
    //  * @param integer $pay_role 1默认货主,2=司机
    //  * @return void
    //  */
    // public function get_wxpay_params($pay_role=1){
    //     $config = Config::get('site');
    //     if($pay_role==1){
    //         $params = new \Yurun\PaySDK\Weixin\Params\PublicParams;
    //         $params->appID = $config['app_id'];//appid
    //         $params->mch_id = $config['mch_id'];//商户号
    //         $params->key = $config['key'];//秘匙
    //     }else{
    //         //司机端
    //         $params = new \Yurun\PaySDK\Weixin\Params\PublicParams;
    //         $params->appID = $config['driver_app_id'];//appid
    //         $params->mch_id = $config['driver_mch_id'];//商户号
    //         $params->key = $config['driver_key'];//秘匙
    //     }
        


    //     return $params;      
    // }


    /**
     * 查询阿里支付钱包
     * 
     * @param string $order
     * @return void
     */
    public function ali_pay_money_order_query($order='Money2021122016513820',$self=null)
    {
        // if(!$order){
        //     $order_data = Db::name('money_order')->where('rand()')->limit(1)->where('pay_type','2')->find();
        //     $order = $order_data;
        // }else{
            $order_data = Db::name('money_order')->where('order',$order)->find();
        // }

        if(!$order_data){
            $this->error('没有该订单信息');
        }
        // halt($order_data);

        $this->_params = $this->get_alipay_params($order_data['pay_role']);
        // halt($this->_params);
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->_params);

        // 支付接口
        $request = new \Yurun\PaySDK\AlipayApp\Params\Query\Request();
        $request->notify_url = $this->domain.'/api/query_pay/ali_pay_callback';// 支付后通知地址（作为支付成功回调，这个可靠）
        // $request->return_url = $this->domain; // 支付后跳转返回地址
        $request->businessParams->out_trade_no = $order; // 订单支付时传入的商户订单号,和支付宝交易号不能同时为空。
        // $request->businessParams->trade_no = ''; // 支付宝交易号，和商户订单号不能同时为空

        // 调用接口
        $result = $pay->execute($request);

        var_dump('result:', $result);
        var_dump('success:', $pay->checkResult());
        var_dump('error:', $pay->getError(), 'error_code:', $pay->getErrorCode());
    }

    /**
     * 阿里司机钱包充值回调（非接口）
     * @ApiInternal
     * @return void
     */
    public function ali_pay_callback()
    {

        $params = $this->request->param();
        file_put_contents('./alipaylog/'.$params['out_trade_no'].'ali_pay_callback'.date('Y_m_d_H_i_s').'.txt',json_encode($params));
        $this->_params = $this->get_alipay_params(1);
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->_params);
        if($pay->verifyCallback($_POST))
        {
            file_put_contents('./alipaylog/'.$params['out_trade_no'].'success'.date('Y_m_d_H_i_s').'.txt',json_encode($params));
            // 通知验证成功，可以通过POST参数来获取支付宝回传的参数
            $order = $params['out_trade_no'];
            $order_data = Db::name('money_order')->where('order',$order)->find();
            if(!$order_data){
                $this->error('没有该订单号');
            }
            if($order_data['pay_status']=='1' || $order_data['pay_status']=='4'){//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $up_data['pay_time'] = strtotime($params['gmt_payment']);
                $up_data['pay_update_time'] = strtotime($params['notify_time']);
                $up_data['pay_status'] = '2';
                $up_data['pay_openid'] = $params['buyer_id'];
                $up_data['pay_money'] = $params['total_amount']*100;//实际支付（分）

                $money_data = $this->IncUserMoney($order_data['uid'],$order_data['money'],'支付宝充值',$order_data['id']);
                $up_data['before'] = $money_data['before'];
                $up_data['after'] = $money_data['after'];

                Db::name('money_order')->where('order',$order)->update($up_data);
                echo 'success';
            }

        }
        else
        {
            $this->AliUpdatePayOrderPayStatus($params);
            // if($params['trade_status']=='TRADE_SUCCESS'){
            //     $order = $params['out_trade_no'];
            //     $order_data = Db::name('money_order')->where('order',$order)->find();
            //     if(!$order_data){
            //         $this->error('没有该订单号');
            //     }
            //     if($order_data['pay_status']=='1' || $order_data['pay_status']=='4'){//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
            //         $up_data['pay_time'] = strtotime($params['gmt_payment']);
            //         $up_data['pay_update_time'] = strtotime($params['notify_time']);
            //         $up_data['pay_status'] = '2';
            //         $up_data['pay_openid'] = $params['buyer_id'];
            //         $up_data['pay_money'] = $params['total_amount']*100;//实际支付（分）

            //         $money_data = $this->IncUserMoney($order_data['uid'],$order_data['money'],'支付宝充值',$order_data['id']);
            //         $up_data['before'] = $money_data['before'];
            //         $up_data['after'] = $money_data['after'];

            //         Db::name('money_order')->where('order',$order)->update($up_data);
            //         echo 'success';
            //     }
            // }
           
        }

        
        // halt($params);
        
    }




    /**
     * 阿里货主钱包充值回调（非接口）
     * @ApiInternal
     * @return void
     */
    public function ali_driver_pay_callback()
    {
        $params = $this->request->param();
        file_put_contents('./alipaylog/'.$params['out_trade_no'].'ali_driver_pay_callback'.date('Y_m_d_H_i_s').'.txt',json_encode($params));
        $this->_params = $this->get_alipay_params(2);
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->_params);
        if($pay->verifyCallback($_POST))
        {
            file_put_contents('./alipaylog/'.$params['out_trade_no'].'driver_success'.date('Y_m_d_H_i_s').'.txt',json_encode($params));
            // 通知验证成功，可以通过POST参数来获取支付宝回传的参数
            $order = $params['out_trade_no'];
            $order_data = Db::name('money_order')->where('order',$order)->find();
            if(!$order_data){
                $this->error('没有该订单号');
            }
            if($order_data['pay_status']=='1' || $order_data['pay_status']=='4'){//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $up_data['pay_time'] = strtotime($params['gmt_payment']);
                $up_data['pay_update_time'] = strtotime($params['notify_time']);
                $up_data['pay_status'] = '2';
                $up_data['pay_openid'] = $params['buyer_id'];
                $up_data['pay_money'] = $params['total_amount']*100;//实际支付（分）
                $money_data = $this->IncUserMoney($order_data['uid'],$order_data['money'],'支付宝司机充值',$order_data['id']);
                $up_data['before'] = $money_data['before'];
                $up_data['after'] = $money_data['after'];
                Db::name('money_order')->where('order',$order)->update($up_data);
                
                echo 'success';
            }
        }
        else
        {
            $this->AliUpdatePayOrderPayStatus($params);
            

            // $content = var_export($_POST, true) . \PHP_EOL . 'verify:' . var_export($pay->verifyCallback($_POST), true);
            // file_put_contents('./alipaylog/'.$params['out_trade_no'].'driver_error'.date('Y_m_d_H_i_s').'.txt',$content);
            // 通知验证失败
        }
       
        // 
    }

    /**
     * 修改支付订单状态
     *
     * @param array $params 接收参数
     * @return void
     */
    protected function AliUpdatePayOrderPayStatus($params){

        if($params['trade_status']=='TRADE_SUCCESS'){
            $order = $params['out_trade_no'];//赋值新变量
            //查询钱包订单
            $order_data = Db::name('money_order')
                        ->where('order',$order)
                        ->find();

            if(!$order_data){

                $pay_order = Db::name('pay_order')
                            ->where('order',$order)
                            // ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();

                if(!$pay_order){
                    $this->error('没有该支付押金订单');
                }


                // halt($pay_order);
                if($pay_order && ($pay_order['pay_status']=='1' || $pay_order['pay_status']=='4')){

                    $data['pay_status'] = '2';//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                    $data['pay_time'] = strtotime($params['gmt_payment']);//支付时间
                    $data['pay_type'] = '2';    //支付类型:1=微信,2=支付宝,9=其他
                    $data['pay_money'] = $params['total_amount']*100;//实际支付的金额 分//invoice_amount

                    $data['pay_openid'] = $params['buyer_id'];

                    //修改押金订单
                    $res_up = Db::name('pay_order')
                            ->where('order',$order)
                            ->update($data);
                    
                    //修改主订单  订单类型:1=普通发货,2=城市快运,3=拉货搬家,4=专线
                    $db = $this->GetTableByOrderStatus($pay_order['order_status']);
                
                    //角色:1=货主,2=司机
                    switch ($pay_order['role_status']) {
                        case '1':
                            $pay_status['spay_status'] = '1';
                            $pay_status['pay_time'] = $data['pay_time'];
                         
                            break;
                        case '2':
                            $pay_status['jpay_status'] = '1';
                            // if($pay_order['order_status']!='4'){//订单类型:1=普通发货,2=城市快运,3=拉货搬家,4=专线
                            //     $pay_status['j_time'] = $data['pay_time'];
                            // }
                            break;
                        default:

                            break;
                    }
                    //修改押金单单支付状态
                    Db::name($db)->where('id',$pay_order['order_id'])->update($pay_status);
                    $this->PushOrderMsg($pay_order['order_status'],$pay_order['order_id']);//推送发布订单消息
                    
                    echo 'success';
                }

                
            }elseif($order_data['pay_status']=='1' || $order_data['pay_status']=='4'){//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $up_data['pay_time'] = strtotime($params['gmt_payment']);
                $up_data['pay_update_time'] = strtotime($params['notify_time']);
                $up_data['pay_status'] = '2';//支付类型:1=微信,2=支付宝,9=其他
                $up_data['pay_openid'] = $params['buyer_id'];
                $up_data['pay_money'] = $params['total_amount']*100;//实际支付（分）
                $money_data = $this->IncUserMoney($order_data['uid'],$order_data['money'],'支付宝司机充值',$order_data['id']);
                $up_data['before'] = $money_data['before'];
                $up_data['after'] = $money_data['after'];
                Db::name('money_order')->where('order',$order)->update($up_data);
                
                echo 'success';
            }
        }else{
            halt($params);
        }
    }

    





    /**
     * 查询微信支付发货人(货主)VIP订单
     * @ApiWeigh (998)
     * @param string $order 订单号
     * @return void
     */
    public function wechat_query_pay_svip_order($order='SCOrder2021032399979710')
    {  


        //微信
        $params = $this->get_wxpay_params($this->pay_role);
        // SDK实例化，传入公共配置
        $sdk = new \Yurun\PaySDK\Weixin\SDK($params);
        // 支付接口
        $request = new \Yurun\PaySDK\Weixin\OrderQuery\Request;
        $request->out_trade_no = $order;
        $result = $sdk->execute($request);

        // $this->success('result:', $result);
        // $this->success('success:', $sdk->checkResult());
        // $this->success('error:', $sdk->getError(), 'error_code:', $sdk->getErrorCode());

        //查询是否支付成功
        if($result['result_code'] == 'FAIL'){//此订单没有支付过 ！微信未记录
            $this->error($result['err_code_des'],$result);
        }
        //trade_state自动成功就说明支付成功了！
        if ($result['return_code'] == 'SUCCESS' && $result['trade_state'] == 'SUCCESS') {
            //查询如果还没修改订状态就修改状态 ，
            // 统一写成返回支付等信息等必要字段；
            $order_data = Db::name('svip_order')
                            ->where('order',$order)
                            ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();
            if($order_data){
                $data['pay_status'] = '2';//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $data['pay_time'] = strtotime($result['time_end']);//支付时间
                $data['pay_type'] = '1';    //支付类型:1=微信,2=支付宝,9=其他
                $data['pay_money'] = $result['total_fee'];//实际支付的金额 分

                $data['pay_openid'] = $result['openid'];
    
                $res_up = Db::name('svip_order')
                        ->where('order',$order)
                        ->update($data);
                
                
                $this->AddUserSVipEtimeByOrder($order);//增加用户的vip 时间 购买订单

            }

            // return json($result);
            $this->success('更新支付成功',$result);


        }else{
            // return json($result);
            $this->success('ok',$result);
        }
    
        // $orderdata = $this->get_order_data($order);
        // return json($orderdata);

    }




    /**
     * 查询微信支付司机VIP订单
     * @ApiWeigh (998)
     * @param string $order 订单号
     * @return void
     */
    public function wechat_query_pay_jvip_order($order='SCOrder2021032399979710')
    {  


        //微信
        $params = $this->get_wxpay_params($this->pay_role);
        // SDK实例化，传入公共配置
        $sdk = new \Yurun\PaySDK\Weixin\SDK($params);
        // 支付接口
        $request = new \Yurun\PaySDK\Weixin\OrderQuery\Request;
        $request->out_trade_no = $order;
        $result = $sdk->execute($request);

        // $this->success('result:', $result);
        // $this->success('success:', $sdk->checkResult());
        // $this->success('error:', $sdk->getError(), 'error_code:', $sdk->getErrorCode());

        //查询是否支付成功
        if($result['result_code'] == 'FAIL'){//此订单没有支付过 ！微信未记录
            $this->error($result['err_code_des'],$result);
        }
        //trade_state自动成功就说明支付成功了！
        if ($result['return_code'] == 'SUCCESS' && $result['trade_state'] == 'SUCCESS') {
            //查询如果还没修改订状态就修改状态 ，
            // 统一写成返回支付等信息等必要字段；
            $order_data = Db::name('jvip_order')
                            ->where('order',$order)
                            ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();
            if($order_data){
                $data['pay_status'] = '2';//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $data['pay_time'] = strtotime($result['time_end']);//支付时间
                $data['pay_type'] = '1';    //支付类型:1=微信,2=支付宝,9=其他
                $data['pay_money'] = $result['total_fee'];//实际支付的金额 分

                $data['pay_openid'] = $result['openid'];
    
                $res_up = Db::name('jvip_order')
                        ->where('order',$order)
                        ->update($data);
                
                
                $this->AddUserJVipEtimeByOrder($order);//增加用户的vip 时间 购买订单

            }

            // return json($result);
            $this->success('更新支付成功',$result);


        }else{
            // return json($result);
            $this->success('ok',$result);
        }
    
        // $orderdata = $this->get_order_data($order);
        // return json($orderdata);

    }


    /**
     * 查询微信充值钱包订单
     * @ApiWeigh (998)
     * @param string $order 订单号
     * @return void
     */
    public function wechat_query_pay_money_order($order='Money2021122015534220',$self=null)
    {          
         $order_data = Db::name('money_order')
                    ->where('order',$order)
                    ->find();
        //微信
        $params = $this->get_wxpay_params($order_data['pay_role']);
 
        // SDK实例化，传入公共配置
        $sdk = new \Yurun\PaySDK\Weixin\SDK($params);
        // 支付接口
        $request = new \Yurun\PaySDK\Weixin\OrderQuery\Request;
        $request->out_trade_no = $order;
        $result = $sdk->execute($request);

        //查询是否支付成功
        if($result['result_code'] == 'FAIL'){//此订单没有支付过 ！微信未记录
            $this->error($result['err_code_des'],$result);
        }
        //trade_state自动成功就说明支付成功了！
        if ($result['return_code'] == 'SUCCESS' && $result['trade_state'] == 'SUCCESS') {
            //查询如果还没修改订状态就修改状态 ，
            // 统一写成返回支付等信息等必要字段；
            $order_data = Db::name('money_order')
                            ->where('order',$order)
                            ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();

            // halt($order_data);
            if($order_data){
                $data['pay_status'] = '2';//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $data['pay_time'] = strtotime($result['time_end']);//支付时间
                $data['pay_type'] = '1';    //支付类型:1=微信,2=支付宝,9=其他
                $data['pay_money'] = $result['total_fee'];//实际支付的金额 分

                $data['pay_openid'] = $result['openid'];

                $money_data = $this->IncUserMoney($order_data['uid'],$order_data['money'],'微信充值',$order_data['id']);
                $up_data['before'] = $money_data['before'];
                $up_data['after'] = $money_data['after'];
    
                $res_up = Db::name('money_order')
                        ->where('order',$order)
                        ->update($data);
                // $this->IncUserMoney($order_data['uid'],$order_data['money'],$order.'微信充值');
                
 
            }
            if($self)
                return true;

            // return json($result);
            $this->success('更新支付成功',$result);


        }else{
            if($self)
                return false;
            // return json($result);
            $this->success('ok',$result);
        }
    
        // $orderdata = $this->get_order_data($order);
        // return json($orderdata);

    }



    /**
     * 查询微信支付订单
     * @ApiWeigh (998)
     * @param string $order 订单号
     * @return void
     */
    public function wechat_query_pay_order($order='OrderS20210916164618345999953102')
    {   

        
        $order_data = Db::name('pay_order')
                            ->where('order',$order)
                            // ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();
        //微信
        $params = $this->get_wxpay_params($order_data['role_status']);
        // SDK实例化，传入公共配置
        $sdk = new \Yurun\PaySDK\Weixin\SDK($params);
        // 支付接口
        $request = new \Yurun\PaySDK\Weixin\OrderQuery\Request;
        $request->out_trade_no = $order;
        $result = $sdk->execute($request);

        //查询是否支付成功
        if($result['result_code'] == 'FAIL'){//此订单没有支付过 ！微信未记录
            $this->error($result['err_code_des'],$result);
        }
        //trade_state自动成功就说明支付成功了！
        if ($result['return_code'] == 'SUCCESS' && $result['trade_state'] == 'SUCCESS') {
            //查询如果还没修改订状态就修改状态 ，
            // 统一写成返回支付等信息等必要字段；
            $order_data = Db::name('pay_order')
                            ->where('order',$order)
                            ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                            ->find();

            // halt($order_data);
            if($order_data){
                $data['pay_status'] = '2';//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                $data['pay_time'] = strtotime($result['time_end']);//支付时间
                $data['pay_type'] = '1';    //支付类型:1=微信,2=支付宝,9=其他
                $data['pay_money'] = $result['total_fee'];//实际支付的金额 分

                $data['pay_openid'] = $result['openid'];
    
                $res_up = Db::name('pay_order')
                        ->where('order',$order)
                        ->update($data);
                
                //修改主订单  订单类型:1=普通发货,2=城市快运,3=拉货搬家,4=回程单
                $db = $this->GetTableByOrderStatus($order_data['order_status']);
             
                //角色:1=货主,2=司机
                switch ($order_data['role_status']) {
                    case '1':
                        $pay_status['spay_status'] = '1';
                        $pay_status['pay_time'] = $data['pay_time'];
                        break;
                    case '2':
                        $pay_status['jpay_status'] = '1';
                        break;
                    default:
                        # code...
                        break;
                }
                Db::name($db)->where('id',$order_data['order_id'])->update($pay_status);
                
                $this->PushOrderMsg($order_data['order_status'],$order_data['order_id']);//推送发布订单消息
                // $class=$this->verify_class_id($order_data['class_id']);

                //添加机构流水 状态:1=买课程,2=老师提现,3=平台缴费,4=未知
                // $this->add_bill_jigou($order_data['admin_id'],'1',round($data['pay_money']/100,2),$order,'购买-'.$class['class_name']);    
                // $this->Inc_class_sales($order_data['class_id']);//增加课程销量
            }

            // return json($result);
            $this->success('更新支付成功',$result);


        }else{
            // return json($result);
            $this->success('ok',$result);
        }
    
        // $orderdata = $this->get_order_data($order);
        // return json($orderdata);

    }
    
  








    /**
     * 超时处理(非接口)
     *
     * @return void
     */
    public function overtime()
    {
        $all = 0;
        $config = Config::get('site');
        $overtime['money_order'] = 60;  //充值钱包超时
        $overtime['order1'] = 15*60;    
        $overtime['order1_s_time'] = $config['s_timeout']*60; //发货人未支付
        $overtime['order1_j_time'] = $config['j_timeout']*60; //司机未支付

        $overtime['order2'] = 15*60;
        $overtime['order2_s_time'] = $config['s_timeout']*60; //发货人未支付
        $overtime['order2_j_time'] = $config['j_timeout']*60; //司机未支付
        $overtime['order4'] = 15*60;
        $overtime['jvip_order'] = 15*60;
        $overtime['jigou'] = 15*60;



        $class_list = Db::name('money_order')
                ->where('time','<',time()-$overtime['money_order'])
                // ->order('time desc')
                ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                ->select();
        $ci = 0;
        foreach ($class_list as $key => $val) {
            // halt($val);
            // var_dump($val);
            if($val['pay_type']=='1'){//微信支付
                try {
                    $this->wechat_query_pay_money_order($val['order'],true);
                    $ci++;
                } catch (\Throwable $th) {
                    //throw $th;
                }
               
            }else{
                try {
                    $this->ali_pay_money_order_query($val['order'],true);
                    $ci++;
                } catch (\Throwable $th) {
                    //throw $th;
                }
               
            }
            
        }
        $res['充值钱包'] = $ci;
        $all = $ci+$all;



        //查询接单后未支付的用户
        $order1_j_order_ids = Db::name('order1')
                ->where('j_uid','>',0)
                ->where('jpay_status','2')//接单人支付押金:1=已支付,2=未支付,3=已违约
                ->where('j_time','<',time()-$overtime['order1_j_time'])
                ->column('id');

        // $res['押金订单超时order1'] = $ci = Db::name('pay_order')
        //         ->where('order_status','1')
        //         ->where('time','<',time()-$overtime['order1'])
        //         ->where('pay_status','1')
        //         ->update(['pay_status'=>'4']);//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                // ->select();
                
        $res['司机押金支付订单超时order1'] = $ci = Db::name('pay_order')
                ->where('role_status','2')//角色:1=货主,2=司机
                ->where('order_status','1')//订单类型:1=普通发货,2=城市快运,3=拉货搬家,4=顺风车
                // ->where('time','<',time()-$overtime['order1'])
                ->where('order_id','in',$order1_j_order_ids)
                ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                ->update(['pay_status'=>'4']);
        $all = $ci+$all;

        $res['取消司机押金支付订单超时order1']  = $ci = Db::name('order1')
                ->where('id','in',$order1_j_order_ids)
                ->update(['j_uid'=>null,'j_time'=>null,'status'=>'1']);
        $all = $ci+$all;


        //查询货主发单后未支付的
        $order1_s_order_ids = Db::name('order1')
                ->where('s_uid','>',0)
                ->where('spay_status','2')//发货人支付押金:1=已支付,2=未支付,3=已违约
                ->where('time','<',time()-$overtime['order1_s_time'])
                ->column('id');
                
        $res['货主押金支付订单超时order1'] = $ci = Db::name('pay_order')
                ->where('role_status','1')//角色:1=货主,2=司机
                ->where('order_status','1')//订单类型:1=普通发货,2=城市快运,3=拉货搬家,4=顺风车
                // ->where('time','<',time()-$overtime['order1'])
                ->where('order_id','in',$order1_s_order_ids)
                ->where('pay_status','1')//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
                ->update(['pay_status'=>'4']);
        $all = $ci+$all;
        //货主未支付的订单不能让其他用户看见
        // $res['取消货主押金支付订单超时order1'] = $ci = Db::name('order1')
        //         ->where('id','in',$order1_s_order_ids)
        //         ->update(['s_uid'=>null,'time'=>null]);


            
        $res['押金订单超时order2'] = $ci = Db::name('pay_order')
                ->where('order_status','2')
                ->where('time','<',time()-$overtime['order2'])
                ->where('pay_status','1')
                ->update(['pay_status'=>'4']);//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        $all = $ci+$all;

        $res['押金订单超时order4'] = $ci = Db::name('pay_order')
                ->where('order_status','4')
                ->where('time','<',time()-$overtime['order4'])
                ->where('pay_status','1')
                ->update(['pay_status'=>'4']);//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        $all = $ci+$all;


        // //查询待支付的vip订单
        // $vip_order = Db::name('jvip_order')
        //         ->where('time','<',time()-$overtime['jvip_order'])
        //         ->where('pay_status','1')
        //         ->select();

        // foreach ($pro_list as $key => $val) {
        //     $this->wechat_query_pay_jvip_order($val['order']);
        // }

       


        //押金订单超时
        // $res['pay_order'] = $ci = Db::name('pay_order')
        //             ->where('time','<',time()-$overtime['order1'])
        //             ->where('pay_status','1')
        //             ->setField('pay_status', '4');//支付状态:1=待支付,2=已支付,3=已退款,4=已超时




        // 司机押金订单超时
        $ci = 0;
        $j_list = Db::name('pay_order')
                    ->where('time','<',time()-$overtime['order1'])
                    ->where('role_status','2')//角色:1=货主,2=司机
                    ->where('pay_status','1')
                    ->select();
        foreach ($j_list as $key => $val) {        
            $db_order = $this->GetTableByOrderStatus($val['order_status']);//获取数据库的表
            $order = Db::name($db_order)
                ->where('id',$val['order_id'])
                ->where('jpay_status','2')//接单人支付押金:1=已支付,2=未支付,3=已违约
                ->where('status','2')//状态:1=待接单,2=已接单,3=已完成,9=已取消
                ->update(['j_uid'=>'' , 'j_time'=>'' , 'status'=>'1']);
            if($order)
                $ci++;

        }
        $res['司机押金订单超时'] = $ci;
        $all = $ci+$all;

        $res['城市搬家司机未支付押金订单超时'] = $ci = Db::name('order2')
                ->where('j_uid','>',0)
                ->where('jpay_status','2')//接单人支付押金:1=已支付,2=未支付,3=已违约
                ->where('j_time','<',time()-$overtime['order2_j_time'])
                ->update(['j_uid'=>'' , 'j_time'=>'' , 'status'=>'1']);
        $all = $ci+$all;
        $res['顺风车货主未支付押金订单超时'] = $ci = Db::name('order_return')
                ->where('s_uid','>',0)
                ->where('spay_status','2')//接单人支付押金:1=已支付,2=未支付,3=已违约
                ->where('j_time','<',time()-$overtime['order1_s_time'])
                ->update(['s_uid'=>'' , 'j_time'=>'' , 'status'=>'1']);
        $all = $ci+$all;

        
        
                    // ->setField('pay_status', '4');//支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        if($all>0)
        return json($res);
        echo '0';
    }

}